package utgame.com.fakelegendary.container;

import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import utgame.com.fakelegendary.model.Friend;
import utgame.UtMessage.MS_RequestFriends;
import utgame.UtMessage.PlayerInfo;
import utgame.com.fakelegendary.model.SortFriendByOnline;

/**
 * Created by xueal on 2018/1/20.
 */

public class FriendManager {
    private static final FriendManager single = new FriendManager();
    public static FriendManager getInstance() { return single; }


    private Map<String, Friend> mFriendMap = new HashMap<>();

    private List<Friend> mFriendList = new ArrayList<>();

    // 指向同一份内存
    public final Map<String, Friend> getFriendMap() {return mFriendMap;}
    public final List<Friend> getFriendList() {return mFriendList;}

    public void saveFriends(byte[] message){
        MS_RequestFriends requestFriends = null;
        try {
            requestFriends = MS_RequestFriends.parseFrom(message);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        if (requestFriends == null) return;

        List<PlayerInfo> playerInfoList = requestFriends.getFriedsList();
        for (int i = 0; i < playerInfoList.size(); ++i){
            Friend friend = new Friend(Friend.imageIds[i % Friend.imageIds.length], playerInfoList.get(i).getName(), playerInfoList.get(i).getIsOnline());
            mFriendMap.put(playerInfoList.get(i).getName(), friend);
            mFriendList.add(friend);
        }
        Collections.sort(mFriendList, new SortFriendByOnline());
    }
    public void updateFriendOnline(String name, boolean isOnline){
        Friend friend = mFriendMap.get(name);
        if (friend == null) return;

        friend.setOnline(isOnline);
    }

    public Friend getFriend(String name){
        return mFriendMap.get(name);
    }

    public void destroy(){
        mFriendMap.clear();
        mFriendList.clear();
    }

}
